<template>
  <div ref="messageList" class="chat">
    <x-header  @on-click-back="goBack" :left-options="{preventGoBack: true}">{{$store.state.chat.contact.UserCode}}</x-header>
    <load-more v-if="showLoading||tip==='已加载全部'||tip==='暂无聊天记录'" :show-loading="showLoading" :tip="tip"></load-more>
    <div class="list">
      <div class="item"
           v-for="(item, index) in messages"
           :key="index"
           :class="{right: $store.state.user.uid === item.senderId}">
        <p class="date" :class="{dateShow: showTime(index)}"><small>{{ item.timestamp | cHHmm }}</small></p>
        <div class="msg-wrap">
          <img class="avatar" src="../../assets/avatar.jpg">
          <span class="content">{{ item.message }}</span>
        </div>
      </div>
    </div>
    <div class="input-wrap">
      <x-input type="text" placeholder="说点什么..." v-model="message"></x-input>
      <img @click="sendMsg" class="send-btn" src="../../assets/send.png" alt="">
    </div>
  </div>
</template>

<script>
import {
  XHeader,
  Group,
  Cell,
  XButton,
  XInput,
  LoadMore
} from 'vux'
import {
  getChatHistory,
  insertChat,
  disposeNoWriteMsg
} from '../../api/api'
import moment from 'moment'
export default {
  name: 'chat',
  components: {
    XHeader,
    Group,
    Cell,
    XButton,
    XInput,
    LoadMore
  },
  data () {
    return {
      messages: [],
      message: '',
      showLoading: true,
      upload: false,
      tip: '正在加载',
      hasNewMsg: false
    }
  },
  watch: {
    '$store.state.chat.chatMessage' (message) {
      const user = this.$store.state.user
      const contact = this.$store.state.chat.contact
      if ((message.senderId === user.uid && message.receiverId === contact.senderId) || (message.receiverId === user.uid && message.senderId === contact.senderId)) {
        this.messages.push(message)
        if (!this.hasNewMsg) {
          this.hasNewMsg = true
        }
        setTimeout(() => {
          this.scrollToBottom()
        }, 100)
      }
    }
  },
  mounted () {
    this.getChatHistory()
    const messageList = this.$refs.messageList
    messageList.addEventListener('scroll', this.scrollEvent, false)
  },
  beforeDestroy () {
    const messageList = this.$refs.messageList
    messageList.removeEventListener('scroll', this.scrollEvent, false)
  },
  methods: {
    scrollEvent () {
      var st = this.$refs.messageList.scrollTop
      if (st === 0) {
        this.upload = true
        this.getChatHistory()
      }
    },
    sendMsg () {
      if (!this.message.trim()) {
        this.$vux.toast.text('请输入内容')
        return
      }
      const user = this.$store.state.user
      const contact = this.$store.state.chat.contact
      insertChat({
        chatContent: this.message,
        receiverId: contact.senderId,
        senderId: user.uid,
        messageId: '',
        createTime: moment().valueOf()
      }).then(res => {
        if (res.status === 200) {
          this.message = ''
          this.upload = false
        } else {
          this.$vux.toast.text(res.msg)
        }
      })
    },
    scrollToTop () {
      this.$refs.messageList.scrollTop = 600
    },
    scrollToBottom () {
      setTimeout(() => {
        this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight
      }, 100)
    },
    onSubmit () {
      if (!this.message.trim()) {
        this.$vux.toast.text('请输入内容')
        return
      }
      this.message = ''
    },
    goBack () {
      this.$router.back()
      if (this.hasNewMsg) {
        this.disposeNoWriteMsg()
      }
      this.$store.state.chat.contact = {}
    },
    disposeNoWriteMsg () {
      const contact = this.$store.state.chat.contact
      disposeNoWriteMsg({
        friUserId: contact.senderId
      }).then(res => {
        if (res.status === 200) {
        } else {
          this.$vux.toast.text(res.msg)
        }
      })
    },
    getChatHistory (callback = () => {}) {
      const contact = this.$store.state.chat.contact
      const user = this.$store.state.user
      this.showLoading = true
      getChatHistory({
        senderId: contact.senderId,
        receiverId: user.uid,
        startTimestamp: this.messages.length ? this.messages[0].timestamp : moment().valueOf()
      }).then(res => {
        this.showLoading = false
        if (res.status === 200) {
          const data = res.data
          if (this.upload) {
            if (!data.length) {
              this.tip = '已加载全部'
              return
            }
            for (let i = data.length - 1; i >= 0; i--) {
              this.messages.unshift(data[i])
            }
            this.scrollToTop()
          } else {
            if (!data.length) {
              this.tip = '暂无聊天记录'
              return
            }
            this.messages = data
            this.scrollToBottom()
          }
          callback()
        } else {
          this.$vux.toast.text(res.msg)
        }
      })
    },
    showTime (index) {
      return index ? (this.messages[index].timestamp - this.messages[index - 1].timestamp >= 60000 ? 1 : 0) : 1
    }
  }
}
</script>

<style lang="less">
.chat{
  position: absolute;
  top: 46px;
  right: 0;
  bottom: 55px;
  left: 0;
  overflow-y: auto;
  font-size: 16px;
  .weui-loadmore{
    margin: 2.4em auto 0 auto;
  }
  .list{
    height: 100%;
    /*background-color: #ececec;*/
    padding: 0 10px 55px 10px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    .item{
      position: relative;
      margin-top: 10px;
      overflow: hidden;
      &.right .msg-wrap{
        padding-left: 0;
        padding-right: 50px;
        text-align: right;
        .avatar{
          left: auto;
          right: 0;
        }
        .content:before{
          left: auto;
          right: -5px;
          border-right: 0;
          border-left: 5px solid #ffffff;
        }
      }
      .date{
        text-align: center;
        margin: 5px 0;
        display: none;
        small{
          color: #ffffff;
          display: inline-block;
          background-color: #b7b7b7;
          padding: 0 5px;
          -webkit-border-radius: 4px;
          -moz-border-radius: 4px;
          border-radius: 4px;
        }
        &.dateShow{
          display: block;
        }
      }
      .msg-wrap{
        padding-left: 50px;
        position: relative;
        .avatar{
          width: 40px;
          height: 40px;
          -webkit-border-radius: 4px;
          -moz-border-radius: 4px;
          border-radius: 4px;
          position: absolute;
          top: 0;
          left: 0;
        }
        .content{
          display: inline-block;
          background-color: #ffffff;
          padding: 7px 10px;
          -webkit-border-radius: 4px;
          -moz-border-radius: 4px;
          border-radius: 4px;
          border: 1px solid #e2e2e2;
          position: relative;
          &:before{
            display: inline-block;
            content: '';
            border-top: 5px solid transparent;
            border-bottom: 5px solid transparent;
            border-right: 5px solid #ffffff;
            top: 50%;
            -webkit-transform: translateY(-50%);
            transform: translateY(-50%);
            left: -5px;
            position: absolute;
          }
        }
      }
    }
  }
  .input-wrap{
    z-index: 99;
    position: fixed;
    bottom: 0;
    height: 55px;
    width: 100%;
    padding-right: 30px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    .send-btn{
      width: 28px;
      height: 28px;
      position: absolute;
      right: 10px;
      top: 10px
    }
  }
}
</style>
